<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {cloneDeep} from "lodash";
import {addSysRole, getSysRole, updateSysRole} from "@/api/system/role";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  id: undefined,
  roleName: '',
  roleCode: ''
})
const rules = reactive({
  roleName: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
  roleCode: [{required: true, message: '请输入角色编码', trigger: 'blur'}]
})
const formType = ref('create')


const open = async (id, type = 'create') => {
  formType.value = type;
  resetForm();
  if (type === 'create') {
  } else {
    const {data} = await getSysRole(id);
    formData.value = {
      ...data
    }
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  await formRef.value.validate();
  let data = cloneDeep(formData.value);
  if (data.id === undefined) {
    await addSysRole(data);
    proxy.$modal.okNotify('新增成功');
  } else {
    await updateSysRole(data);
    proxy.$modal.okNotify('修改成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    id: undefined,
    roleName: '',
    roleCode: ''
  }
}

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" :modalTitle="`${formType === 'create' ? '新建' : '编辑'}角色`" modalWidth="500px"
               @submit="handleSubmit">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="formData.roleCode" placeholder="请输入角色编码"/>
      </el-form-item>
    </el-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
